const util = require("../../utils/util.js");
var app = getApp();
Page({
  data: {
    year: 0,
    weeks: [],
    winHeight: 0,//窗口高度
    currentTab: 0, //预设当前项的值
    weekList: [],
    loading: false,
    users: wx.getStorageSync("USERS")
  },
  footerTap: app.footerTap,
  onLoad: function () {
    var that = this;
    util.showLoading();
    var interval = setInterval(function () {
      if (that.data.users && that.data.users.id) {
        clearInterval(interval);
        wx.getStorage({
          key: 'USERS',
          success: function (res) {
          },
        })
      } else {
        wx.getStorage({
          key: 'USERS',
          success: function (res) {
            that.setData({
              users: res.data
            });
          },
        })
      }
    }, 1 * 1500);
    wx.getSystemInfo({
      success: function (res) {
        var clientHeight = res.windowHeight,
          clientWidth = res.windowWidth,
          rpxR = 750 / clientWidth;
        var calc = clientHeight * rpxR - 180;
        that.setData({
          winHeight: calc
        });
      }
    });
    var weeks = [];
    for (var i = 1; i <= 52; i++) {
      weeks.push({ "week": i });
    }
    this.setData({
      weeks: weeks,
      year: new Date().getFullYear(),
      currentTab: this.onWeekNumber()
    });
  },
  onUnload: function () {
    this.setData({
      users: []
    });
  },
  //回滚到本周
  onShow: function () {
    var that = this;
    that.setData({
      users: wx.getStorageSync("USERS"),
      currentTab: that.onWeekNumber()
    });
    var interval = setInterval(function () {
      if (that.data.users && that.data.users.id) {
        clearInterval(interval);
        that.onWeekData();
      }
    }, 1 * 100);
  },
  // 滚动切换标签样式
  switchTab: function (e) {
    if (!this.data.loading) {
      util.showLoading();
      this.setData({
        loading: true,
        currentTab: e.detail.current
      });
      this.onWeekData();
    }
  },
  //点击上一周、下一周
  swichNav: function (e) {
    if (!this.data.loading) {
      util.showLoading();
      var handle = e.currentTarget.dataset.handle;
      var currentTab = this.data.currentTab;
      if (handle == "prev") {
        if (currentTab > 1)
          currentTab = currentTab - 1;
      }
      if (handle == "next") {
        if (currentTab < 52)
          currentTab = currentTab + 1;
      }
      this.setData({
        loading: true,
        currentTab: currentTab
      });
      this.onWeekData();
    }
  },
  onKindToggle: function (e) {
    var id = e.currentTarget.dataset.id, dataList = this.data.weekList;
    for (var i = 0, len = dataList.length; i < len; ++i) {
      if (dataList[i].id == id) {
        dataList[i].open = !dataList[i].open
      } else {
        dataList[i].open = false
      }
    }
    this.setData({
      weekList: dataList
    });
  },
  onWeekData: function () {
    var that = this;
    var weekData = new Array('星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六');
    var curweek = that.data.currentTab + 1;
    var basweek = that.onWeekNumber() + 1;
    var weekList = [];
    var date = new Date();
    var day = date.getDay() || 7;
    
    var time = new Date(date.getFullYear(), date.getMonth(), date.getDate() + 1 - day);
    if (curweek > basweek) {
      var $d = (curweek - basweek) * 7;
      date = new Date(time.getFullYear(), time.getMonth(), time.getDate() + $d);
    }
    if (curweek < basweek) {
      var $d = (basweek - curweek) * 7;
      date = new Date(time.getFullYear(), time.getMonth(), time.getDate() - $d);
    }
    if (basweek == curweek) {
      date = time;
    }
    for (var i = 0; i < 7; i++) {
      var $date = new Date(date.getFullYear(), date.getMonth(), date.getDate() + i);
      var week = weekData[$date.getDay()];
      if (util.fdate(new Date(), "MM-DD") == util.fdate($date,"MM-DD")){
        week = weekData[$date.getDay()] + " (今天)";
      }
      var weeks = {
        id: util.fdate($date, "YYYY-MM-DD"),
        date: $date.getMonth() + 1 + "月" + $date.getDate() + "日",
        week: week,
        am: "无日程",
        pm: "无日程",
        open: false
      }
      weekList.push(weeks);
      var parmas = {
        "date": weeks.id,
        "uid": that.data.users.id,
        "tid": that.data.users.teamId
      }
      if (parmas.uid && parmas.uid > 0 && parmas.tid && parmas.tid != "") {
        var isCache = false;
        var weeks = wx.getStorageSync(parmas.tid + ":week:" + parmas.date)
        if (weeks) {
          weekList[i] = weeks;
          isCache = true;
          util.hideToast();
        }
        if (!isCache) {
          util.wxPost({
            url: "/rest/lufei/week", params: parmas,
            success: function (res) {
              var data = res.data.data;
              if (res.data.status == "000") {
                for (var i in weekList) {
                  var weeks = weekList[i];
                  if (weeks.id == data[0].mdate) {
                    var am = false;
                    var pm = false;
                    var amus = "";
                    var pmus = "";
                    for (var ds in data) {
                      var dit = data[ds];
                      if (dit.etime != null) {
                        var et = dit.etime.split(":");
                        if (!pm && et[0] >= 12) {
                          pm = true;
                          pmus = dit.partakeUsers;
                        }
                      }
                      if (dit.btime != null) {
                        var bt = dit.btime.split(":");
                        if (!am && bt[0] <= 12) {
                          am = true;
                          amus = dit.partakeUsers;
                        }
                      }
                    }
                    if (am || pm) {
                      if (am) {
                        weeks.am = amus + " 有日程";
                      }
                      if (pm) {
                        weeks.pm = pmus + " 有日程";
                      }
                      weeks.matterList = res.data.data;
                      weekList[i] = weeks;
                    } else {
                      weeks.matterList = [];
                      weekList[i] = weeks;
                    }
                    wx.setStorage({
                      key: parmas.tid + ":week:" + weeks.id,
                      data: weeks
                    })
                  }
                }
              }
            }
          });
        }
      }
    }
    var interval = setInterval(function () {
      for (var index in weekList) {
        var b = true;
        var week = weekList[index];
        if (typeof (week.matterList) == undefined) {
          b = false;
        }
        if (b) {
          clearInterval(interval);
          util.hideToast();
          that.setData({
            weekList: weekList
          });
          that.setData({
            loading: false
          });
        }
      }
    }, 1 * 500);
  },
  getSystemInfo() {
    try {
      const res = wx.getSystemInfoSync();
      this.setData({
        scrollViewHeight: res.windowHeight * res.pixelRatio || 667
      });
    } catch (e) {
      console.log(e);
    }
  },
  getThisMonthDays(year, month) {
    return new Date(year, month, 0).getDate();
  },
  getFirstDayOfWeek(year, month) {
    return new Date(Date.UTC(year, month - 1, 1)).getDay();
  },
  calculateEmptyGrids(year, month) {
    const firstDayOfWeek = this.getFirstDayOfWeek(year, month);
    let empytGrids = [];
    if (firstDayOfWeek > 0) {
      for (let i = 0; i < firstDayOfWeek; i++) {
        empytGrids.push(i);
      }
      this.setData({
        hasEmptyGrid: true,
        empytGrids
      });
    } else {
      this.setData({
        hasEmptyGrid: false,
        empytGrids: []
      });
    }
  },
  calculateDays(year, month) {
    let days = [];
    const thisMonthDays = this.getThisMonthDays(year, month);
    for (let i = 1; i <= thisMonthDays; i++) {
      days.push(i);
    }
    this.setData({
      days
    });
  },
  //获取当前周
  onWeekNumber: function () {
    var totalDays = 0;
    var date = new Date();
    var years = date.getYear()
    if (years < 1000)
      years += 1900
    var days = new Array(12);
    days[0] = 31;
    days[2] = 31;
    days[3] = 30;
    days[4] = 31;
    days[5] = 30;
    days[6] = 31;
    days[7] = 31;
    days[8] = 30;
    days[9] = 31;
    days[10] = 30;
    days[11] = 31;
    //判断是否为闰年，针对2月的天数进行计算
    if (Math.round(date.getYear() / 4) == date.getYear() / 4) {
      days[1] = 29
    } else {
      days[1] = 28
    }
    if (date.getMonth() == 0) {
      totalDays = totalDays + date.getDate();
    } else {
      var curMonth = date.getMonth();
      for (var count = 1; count <= curMonth; count++) {
        totalDays = totalDays + days[count - 1];
      }
      totalDays = totalDays + date.getDate();
    }
    var week = Math.round(totalDays / 7);
    return week - 1;
  }
})